//
//  FR_HomeViewController.m
//  FaceRecognition
//
//  Created by Sylar on 2017/7/5.
//  Copyright © 2017年 Sylar. All rights reserved.
//

#import "FR_HomeViewController.h"
#import "SY_FunctionView.h"
#import "FR_HomeTopFunctionView.h"
#import "SY_Activity_Model.h"
#import "SY_Activity.h"
#import "ChangeRoleViewController.h"
#import "SY_Home_TeaLeavingViewController.h"
#import "HomeParLeaveListController.h"
#import "FR_VisitortViewController.h"
#import "FR_History_Identity_ViewController.h"
#import "FR_Par_HistoryViewController.h"
#import "FR_AccountViewController.h"
#import "SY_ParentFormViewController.h"//家长报表
#import "FR_ManagerInfoViewController.h"
#import "FR_LateViewController.h"    //迟到
#import "FR_Attendance_ViewController.h" //考勤
#import "FR_AbsentClass_ViewController.h" //旷课
#import "FR_Par_Attendance_ViewController.h" //家长
#import "FR_EnterAndLeaveMessageController.h"
#import "SY_TeacherFormViewController.h"
#import "SY_SchoolFormViewController.h"
#import "FR_MessageListViewController.h"
#import "BPush.h"
#import "FoodListViewController.h"
#import "SYNotiViewController.h"
#import "SYHomeworkViewController.h"
#import "SY_Tch_AttendanceViewController.h"
#import "SY_Par_AttendanceViewController.h"
#import "SY_WebViewController.h"
#import "SYNewDynamicViewController.h"
#import "SY_Tch_OrdersViewController.h"
#import "SY_Par_PaymentListViewController.h"
@interface FR_HomeViewController ()<UIScrollViewDelegate>
{

    NSString *lasttype;
    NSInteger isadviser;
    
    NSTimer *advImgtimer;
    BOOL canFireTimer;
    
    UIImageView *headImg;
    UILabel *nameLabel;
    
    NSArray *funTitleArray;
    NSArray *funIconArray;
    
    NSArray *topFunTitleArray;
    
    UIView *topBackView;
    UIView *funcBackView;
    
    FR_HomeTopFunctionView *top_LeaveView;
    FR_HomeTopFunctionView *top_LateView;
    FR_HomeTopFunctionView *top_AbsenceView;
    FR_HomeTopFunctionView *top_JiLuView;
    
    
    SY_FunctionView *LeaveView;//请假
    SY_FunctionView *attendView; //考勤
    SY_FunctionView *lateView; //迟到
    SY_FunctionView *absenceView;//旷课
    SY_FunctionView *accountView; //统计
    SY_FunctionView *photoView; //底片
    SY_FunctionView *recordView; //记录
    SY_FunctionView *visitorsView; //访客
    SY_FunctionView *foodView;//食谱
    SY_FunctionView *notiView;  //通知
    SY_FunctionView *tasView;   //作业
    SY_FunctionView *campusView;   //校园风采
    SY_FunctionView *dynamicsView;   //班级动态
    SY_FunctionView *schoolPayView;   //校园收费
}

@property (nonatomic, strong) UIButton *changeButton;

@property (nonatomic, strong) UIScrollView *baseScrollView;

@property (nonatomic, strong) UIScrollView *advScrollView;//banner
@property (nonatomic, assign) BOOL advImageLoadSuccess;
@property (nonatomic, strong) UIImageView *pldImageView;
@property (nonatomic, strong) NSArray *advImageArray;
@property (nonatomic, strong) UIPageControl *advPageControl;

@end

@implementation FR_HomeViewController

- (id)init
{
    self = [super init];
    if (self) {
        
        self.hidesBottomBarWhenPushed = NO;
        
    }
    return self;
}

- (void)loadView {
    
    [super loadView];
    
    lasttype = [NSString stringWithFormat:@"%d",[SYAccountTool ShareAccount].account.lasttype];
    
    headImg = [[UIImageView alloc]initWithFrame:CGRectMake(15,  SafeAreaTopHeight - 6 - 32, 32, 32)];
    
    NSString *logo = [SYAccountTool ShareAccount].account.logo;
    if (logo && ![logo hasPrefix:@"http"]) {
        logo = [REQUESTIMAGEURL stringByAppendingString:logo];
    }
    
    [headImg sd_setImageWithURL:[NSURL URLWithString:logo] placeholderImage:[UIImage imageNamed:@"home_title_pic"]];
    headImg.layer.cornerRadius = 16.0;
    headImg.clipsToBounds = YES;
    headImg.hidden = YES;
    [self.navBar addSubview:headImg];
    
    
    nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(headImg.right+8, SafeAreaTopHeight - 14 - 17, 150, 17)];
    [nameLabel setFont:[UIFont systemFontOfSize:16]];
    nameLabel.centerY = headImg.centerY;
    [nameLabel setTextColor:colorFromHex(@"#1e1e1e")];
    
    NSMutableAttributedString *nameAtt;
    if ([lasttype isEqualToString:@"1"]) {
        if ([SYAccountTool ShareAccount].account.haveclass == 0 && [SYAccountTool ShareAccount].account.schoolManage == 0 && [SYAccountTool ShareAccount].account.schoolnum > 0) {//普通员工
            nameAtt = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@(老师)",[SYAccountTool ShareAccount].account.username]];
            [nameAtt addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:NSMakeRange([SYAccountTool ShareAccount].account.username.length, 4)];
        }else if ([SYAccountTool ShareAccount].account.schoolManage > 0){//管理员
            
            nameAtt = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@(管理员)",[SYAccountTool ShareAccount].account.username]];
            [nameAtt addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:NSMakeRange([SYAccountTool ShareAccount].account.username.length, 5)];
        }else {//班主任
            nameAtt = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@(班主任)",[SYAccountTool ShareAccount].account.username]];
            [nameAtt addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:NSMakeRange([SYAccountTool ShareAccount].account.username.length, 5)];
        }
        
    }else if ([lasttype isEqualToString:@"2"]){
        nameAtt = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@(家长)",[SYAccountTool ShareAccount].account.username]];
        [nameAtt addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:NSMakeRange([SYAccountTool ShareAccount].account.username.length, 4)];
    }
    
    nameLabel.attributedText = nameAtt;
    nameLabel.hidden = YES;
    [self.navBar addSubview:nameLabel];
    
    
    self.changeButton = [[UIButton alloc] initWithFrame:CGRectMake(SCREENWIDTH-100, SafeAreaTopHeight - 11- 21, 100, 22)];
    [self.changeButton setImage:[UIImage imageNamed:@"home_title_switch"] forState:UIControlStateNormal];
    //[self.changeButton setTitle:@"切换身份" forState:(UIControlStateNormal)];
    [self.changeButton setTitleColor:colorFromHex(@"3b3b3b") forState:(UIControlStateNormal)];
    [self.changeButton addTarget:self action:@selector(changeRoleAction) forControlEvents:UIControlEventTouchUpInside];
    self.changeButton.hidden = YES;

    [self.navBar addSubview:self.changeButton];
    
}


- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:YES];
    
    lasttype = [NSString stringWithFormat:@"%d",[SYAccountTool ShareAccount].account.lasttype];
    
    NSString *logo = [SYAccountTool ShareAccount].account.logo;
    if (logo && ![logo hasPrefix:@"http"]) {
        logo = [REQUESTIMAGEURL stringByAppendingString:logo];
    }
    
    [headImg sd_setImageWithURL:[NSURL URLWithString:logo] placeholderImage:[UIImage imageNamed:@"switch_nor_"]];
    NSMutableAttributedString *nameAtt;
    
    if ([lasttype isEqualToString:@"1"]) {
        if ([SYAccountTool ShareAccount].account.haveclass == 0 && [SYAccountTool ShareAccount].account.schoolManage == 0 && [SYAccountTool ShareAccount].account.schoolnum > 0) {//普通员工
            nameAtt = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@(老师)",[SYAccountTool ShareAccount].account.username]];
            [nameAtt addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:NSMakeRange([SYAccountTool ShareAccount].account.username.length, 4)];
        }else if ([SYAccountTool ShareAccount].account.schoolManage > 0){//管理员
            
            nameAtt = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@(管理员)",[SYAccountTool ShareAccount].account.username]];
            [nameAtt addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:NSMakeRange([SYAccountTool ShareAccount].account.username.length, 5)];
        }else {//班主任
            nameAtt = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@(班主任)",[SYAccountTool ShareAccount].account.username]];
            [nameAtt addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:NSMakeRange([SYAccountTool ShareAccount].account.username.length, 5)];
        }
        
    }else if ([lasttype isEqualToString:@"2"]){
        nameAtt = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@(家长)",[SYAccountTool ShareAccount].account.username]];
        [nameAtt addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:NSMakeRange([SYAccountTool ShareAccount].account.username.length, 4)];
    }
    
    
    nameLabel.attributedText = nameAtt;
   
    [self requestData];
   
    [self.changeButton setHidden:NO];
    [headImg setHidden:NO];
    [nameLabel setHidden:NO];
    [self getAttendanceCount];
}
- (void)viewDidAppear:(BOOL)animated{
    
    [super viewDidAppear:animated];
    
    [advImgtimer invalidate];
    advImgtimer = [NSTimer scheduledTimerWithTimeInterval:4 target:self selector:@selector(switchAdvImg) userInfo:nil repeats:YES];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:YES];
    
    [self.changeButton setHidden:YES];
    [headImg setHidden:YES];
    [nameLabel setHidden:YES];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager.operationQueue cancelAllOperations];
    
    [advImgtimer invalidate];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadHomeUI) name:@"ChangeHomeUI" object:nil];
    //接收广告页消失的通知，此时开启轮播，避免轮播第一张图片显示时间太短
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(advimageDisapper) name:@"advimageDisapper" object:nil];
    
    [self.view addSubview:self.baseScrollView];
    [self.baseScrollView addSubview:self.advScrollView];
    [self.advScrollView addSubview:self.pldImageView];//加载动画
    
    
    [self loadAdvImage];
    [self configureUI];
    [self contigureFunctions];
    
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    
    NSDictionary *notiDict = delegate.notiDict;
    
    if (notiDict) {
        
        if (!USERID) {
            return;
        }
        
        NSDictionary *dict = [notiDict objectForKey:@"UIApplicationLaunchOptionsRemoteNotificationKey"];
        
        NSString *classidStr = [NSString stringWithFormat:@"%@",[dict objectForKey:@"classid"]];
        NSString *infoidStr = [NSString stringWithFormat:@"%@",[dict objectForKey:@"infoid"]];
        NSString *eventidStr = [NSString stringWithFormat:@"%@",[dict objectForKey:@"eventid"]];
        NSInteger moveto = [[dict objectForKey:@"moveto"] integerValue];
        
        NSString *msgid = [NSString stringWithFormat:@"%@",[notiDict objectForKey:@"msgid"]];
        
        //清空推送列表
        [[UIApplication sharedApplication] setApplicationIconBadgeNumber: 1];
        [[UIApplication sharedApplication] cancelAllLocalNotifications];
        [[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];
        
        [BPush clearAllLocalNotifications];
        
//        SY_Activity_Model *model = [[SY_Activity_Model alloc] init];
//        model.classid = classidStr;
//        model.infoid = infoidStr;
//        model.moveto = moveto;
//        model.apptype = 2;
//        model.eventid = eventidStr;
//        model.messageid = msgid;
//
//        if (msgid) {
////            msgId = msgid;
//            //将消息标记为已读
//            [self setMsgHasRead:msgid];
//        }
//
//        [SY_Activity shareActivity].instructionArr = @[model];
//        [[SY_Activity shareActivity] action];
//        delegate.notiDict = nil;
//
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"hasReadMsgDetail" object:model];
   
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

#pragma mark -Notification
- (void)advimageDisapper{
    
    [advImgtimer invalidate];
    canFireTimer = YES;
    
    [self performSelector:@selector(startTimer) withObject:nil afterDelay:4];
}

- (void)startTimer{
    
    [advImgtimer invalidate];
    advImgtimer = [NSTimer scheduledTimerWithTimeInterval:4 target:self selector:@selector(switchAdvImg) userInfo:nil repeats:YES];
}

- (void)reloadHomeUI {
    
    lasttype = [NSString stringWithFormat:@"%d",[SYAccountTool ShareAccount].account.lasttype];
    
    NSMutableAttributedString *nameAtt;
    if ([lasttype isEqualToString:@"1"]) {
        if ([SYAccountTool ShareAccount].account.haveclass == 0 && [SYAccountTool ShareAccount].account.schoolManage == 0 && [SYAccountTool ShareAccount].account.schoolnum > 0) {//普通员工
            nameAtt = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@(老师)",[SYAccountTool ShareAccount].account.username]];
            [nameAtt addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:NSMakeRange([SYAccountTool ShareAccount].account.username.length, 4)];
        }else if ([SYAccountTool ShareAccount].account.schoolManage > 0){//管理员
            
            nameAtt = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@(管理员)",[SYAccountTool ShareAccount].account.username]];
            [nameAtt addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:NSMakeRange([SYAccountTool ShareAccount].account.username.length, 5)];
        }else {//班主任
            nameAtt = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@(班主任)",[SYAccountTool ShareAccount].account.username]];
            [nameAtt addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:NSMakeRange([SYAccountTool ShareAccount].account.username.length, 5)];
        }
        
    }else if ([lasttype isEqualToString:@"2"]){
        nameAtt = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@(家长)",[SYAccountTool ShareAccount].account.username]];
        [nameAtt addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:NSMakeRange([SYAccountTool ShareAccount].account.username.length, 4)];
    }
    
    nameLabel.attributedText = nameAtt;
    
    [self configureUI];
    [self contigureFunctions];
    
}
#pragma mark - Method

- (void)switchAdvImg{
    
    if (self.advImageArray.count > 1) {
        
        [UIView animateWithDuration:0.3 animations:^{
            
            CGPoint offSet = self.advScrollView.contentOffset;
            
            offSet.x += SCREENWIDTH;
            
            self.advScrollView.contentOffset = offSet;
            
        }];
        
        [self scrollViewDidEndDecelerating:self.advScrollView];
    }
}

- (void)configureUI {
    
    float space = SCREENWIDTH/4.0;
    
    [topBackView removeFromSuperview];
    topBackView = nil;
    
    topBackView = [[UIView alloc]initWithFrame:CGRectMake(0, self.advScrollView.bottom, SCREENWIDTH, 109)];
    [topBackView setBackgroundColor:[UIColor whiteColor]];
    [self.baseScrollView addSubview:topBackView];
    
    if ([SYAccountTool ShareAccount].account.haveclass == 0 && [SYAccountTool ShareAccount].account.schoolManage == 0 && [SYAccountTool ShareAccount].account.schoolnum > 0 && [SYAccountTool ShareAccount].account.lasttype == 1) {
        topFunTitleArray = @[@"记录"];
    }else {
        topFunTitleArray = @[@"请假",@"记录"];
        
        for (int i = 0; i < 1; i++) {
            
            UIView *line = [[UIView alloc]initWithFrame:CGRectMake(space + i *space - 0.3, 20, 0.6, 68)];
            [line setBackgroundColor:colorFromHex(@"#979797")];
            [topBackView addSubview:line];
        }
    }
    
    for (int i = 0; i < topFunTitleArray.count; i++) {
        
        FR_HomeTopFunctionView *topView = [[FR_HomeTopFunctionView alloc]initWithFrame:CGRectMake(i*space, 0, space, 109)];
        topView.titleLabel.text = [topFunTitleArray objectAtIndex:i];
        //topView.countLabel.text = @"99";
        if ([[topFunTitleArray objectAtIndex:i] isEqualToString:@"记录"]) {
            topView.countLabel.hidden = YES;
            UIImageView *iconImg = [[UIImageView alloc]initWithFrame:CGRectMake(8, 8, 26, 26)];
            [iconImg setImage:[UIImage imageNamed:@"home_icon_jilu_little"]];
            [topView.bgView addSubview:iconImg];
        }
        topView.tag = i;
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(topViewAction:)];
        [topView addGestureRecognizer:tap];
        
        [topBackView addSubview:topView];
        
        if (topFunTitleArray.count == 2) {
            
            switch (i) {
                case 0:
                    top_LeaveView = topView;
                    break;
                case 1:
                    top_JiLuView = topView;
                    break;

                default:
                    break;
            }
        }
    }
    
    
    
    UIView *spaceLine = [[UIView alloc]initWithFrame:CGRectMake(0, topBackView.bottom, SCREENWIDTH, 10)];
    [spaceLine setBackgroundColor:colorFromHex(@"f4f5f7")];
    [self.baseScrollView addSubview:spaceLine];
}

- (void)contigureFunctions {
    
    [funcBackView removeFromSuperview];
    funcBackView = nil;
    
    if ([lasttype integerValue] == 1) {
        
        if ([SYAccountTool ShareAccount].account.haveclass == 0 && [SYAccountTool ShareAccount].account.schoolManage == 0 && [SYAccountTool ShareAccount].account.schoolnum > 0) {//普通员工
            funTitleArray = @[@"底片",@"菜谱",@"作业",@"通知",@"班级动态",@"校园风采",@"校园收费"];
            funIconArray = @[@"fun_dipian",@"fun_foodLogo",@"zuoye",@"tongzhi_",@"dongtai_",@"xiaoyuanfengcai_",@"xiaoyuanfengcai_"];
            
        }else {//班主任&管理员
            
                funTitleArray = @[@"请假",@"考勤",@"底片",@"菜谱",@"作业",@"通知",@"班级动态",@"校园风采",@"校园收费"];
                funIconArray = @[@"fun_qingjia",@"fun_kaoqin",@"fun_dipian",@"fun_foodLogo",@"zuoye",@"tongzhi_",@"dongtai_",@"xiaoyuanfengcai_",@"xiaoyuanfengcai_"];
        }
        
    }else if ([lasttype integerValue] == 2){//家长
        funTitleArray = @[@"请假",@"考勤",@"底片",@"菜谱",@"作业",@"通知",@"班级动态",@"校园风采",@"校园收费"];
        funIconArray = @[@"fun_qingjia",@"fun_kaoqin",@"fun_dipian",@"fun_foodLogo",@"zuoye",@"tongzhi_",@"dongtai_",@"xiaoyuanfengcai_",@"xiaoyuanfengcai_"];
    }
    
    
    funcBackView = [[UIView alloc]initWithFrame:CGRectMake(0, self.advScrollView.bottom+120, SCREENWIDTH, 327)];
    [funcBackView setBackgroundColor:[UIColor whiteColor]];
    [self.baseScrollView addSubview:funcBackView];
    
    for (int i = 0; i < [funIconArray count]; i++) {
        
        float width = SCREENWIDTH/4.0;
        
        //float spacing = (SCREENWIDTH - 74*4 - 24)/8.0;
        
        int x = i;
        
        SY_FunctionView *funView = [[SY_FunctionView alloc]initWithFrame:CGRectMake(0, 0, width, 109)];
        
        [funView setX: (x % 4) * (width)];
        [funView setY: x / 4 * 109];
        
        [funcBackView addSubview:funView];
        
        funView.tag = i;
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(functionAction:)];
        [funView addGestureRecognizer:tap];
        
        [funView.bgImageView setImage:[UIImage imageNamed:[funIconArray objectAtIndex:i]]];
        [funView.label setText:[funTitleArray objectAtIndex:i]];
        [funView.unreadImg setHidden:YES];
        
        
        int f = i;
       if ([lasttype integerValue] == 1) {
          
          if ([SYAccountTool ShareAccount].account.haveclass == 0 && [SYAccountTool ShareAccount].account.schoolManage == 0 && [SYAccountTool ShareAccount].account.schoolnum > 0) {//普通员工
             
             switch (f) {
                case 0:
                   photoView  = funView;
                   break;
                case 1:
                   foodView = funView;
                   break;
                case 2:
                   tasView = funView;
                   break;
                case 3:
                   notiView = funView;
                   break;
                case 4:
                   dynamicsView = funView;
                   break;
                case 5:
                   campusView = funView;
                   break;
                case 6:
                   schoolPayView = funView;
                   break;
                default:
                   break;
             }
             
          }else {
             
             switch (f) {
                case 0:
                   LeaveView = funView;
                   break;
                case 1:
                   attendView = funView;
                   break;
                case 2:
                   photoView = funView;
                   break;
                case 3:
                   foodView = funView;
                   break;
                case 4:
                   tasView = funView;
                   break;
                case 5:
                   notiView = funView;
                   break;
                case 6:
                   dynamicsView = funView;
                   break;
                case 7:
                   campusView = funView;
                   break;
                case 8:
                   schoolPayView = funView;
                   break;
                default:
                   break;
             }
             
             
             
          }
       }else if ([lasttype integerValue] == 2)
       {
          switch (f) {
             case 0:
                LeaveView = funView;
                break;
             case 1:
                attendView = funView;
                break;
             case 2:
                photoView = funView;
                break;
             case 3:
                foodView = funView;
                break;
             case 4:
                tasView = funView;
                break;
             case 5:
                notiView = funView;
                break;
             case 6:
                dynamicsView = funView;
                break;
             case 7:
                campusView = funView;
                break;
             case 8:
                schoolPayView = funView;
                break;
             default:
                break;
          }
       }
       
    }
}

- (void)setMsgHasRead:(NSString *)msgIdStr {
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]init];
    
    [param setObject:[NSString stringWithFormat:@"%@",msgIdStr] forKey:@"messageid"];
    
    [Utils Java_get:@"api/setMessageState" parameters:param success:^(NSInteger recode, id jsonObject) {
        
        
    } failure:^(NSInteger recode, NSError *error) {
        
    }];
}

#pragma mark - Action

- (void)advAction:(UIGestureRecognizer *)tap {
    
    UIImageView *imageView = (UIImageView *)tap.view;
    NSInteger index = imageView.tag - 1;
    
    NSDictionary *dic = [self.advImageArray objectAtIndex:index];
    
    if ([[dic objectForKey:@"logotype"] isKindOfClass:[NSNull class]]) {
        return;
    }
    
    NSInteger moveto = [[dic objectForKey:@"logotype"] integerValue];
    
    if (moveto > 0) {
        
        SY_Activity_Model *model = [[SY_Activity_Model alloc]init];
        model.apptype = 2;
        model.infoid = [NSString stringWithFormat:@"%@",[dic objectForKey:@"infoid"]];
        model.moveto = moveto;
        model.url = [dic objectForKey:@"url"];
        
        [SY_Activity shareActivity].instructionArr = @[model];
        [[SY_Activity shareActivity] action];
        return;
    }
    
    
}

- (void)changeRoleAction {
    
    ChangeRoleViewController *changeVC = [[ChangeRoleViewController alloc]init];
    
    [self.navigationController pushViewController:changeVC animated:YES];
}

- (void)topViewAction:(UIGestureRecognizer *)tap {
    
    FR_HomeTopFunctionView *topView = (FR_HomeTopFunctionView *)tap.view;
    
    NSString *str = topView.titleLabel.text;
    
    if ([str isEqualToString:@"请假"]) {
        [self topView_Leave];
    }else if ([str isEqualToString:@"迟到"]) {
        [self topView_Late];
    }else if ([str isEqualToString:@"旷课"]) {
        [self topView_Absence];
    }else if ([str isEqualToString:@"记录"]) {
        [self topView_recordAction];
    }
}

- (void)topView_Leave {
    
    
    if ([lasttype isEqualToString:@"1"]) {
        SY_Home_TeaLeavingViewController *leaveVC=[[SY_Home_TeaLeavingViewController alloc]init];

        [self.navigationController pushViewController:leaveVC animated:YES];
       
       
    }else {
        HomeParLeaveListController *leaveListVC=[[HomeParLeaveListController alloc]init];
        
        [self.navigationController pushViewController:leaveListVC animated:YES];
    }
    
}
- (void)topView_Late {
    
    
    
    if ([lasttype integerValue] == 1) {
        
        FR_LateViewController *vc = [[FR_LateViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        
    }else {
        
        FR_Par_Attendance_ViewController *vc = [[FR_Par_Attendance_ViewController alloc] init];
        vc.arrival = 2;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}
- (void)topView_Absence {
    
    if ([lasttype integerValue] == 1) { //老师身份
        
        FR_AbsentClass_ViewController *vc = [[FR_AbsentClass_ViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }else { //家长身份
        
        FR_Par_Attendance_ViewController *vc = [[FR_Par_Attendance_ViewController alloc] init];
        vc.arrival = 0;
        [self.navigationController pushViewController:vc animated:YES];
    }

}
- (void)topView_recordAction {
    
//    NSString * UrlStr = @"synewspaper://moveto=3002&infoid=3";
//    
//    NSURL * url = [NSURL URLWithString:UrlStr];
//    
//    // 在这里可以先做个判断
//    if ([[UIApplication sharedApplication]canOpenURL:url]) {
//        
//        [[UIApplication sharedApplication] openURL:url];
//        
//    }else{
//        
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"跳转的应用程序未安装" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
//        
//        [alert show];
//    }
    
    if ([lasttype isEqualToString:@"1"]) {
        FR_History_Identity_ViewController *VC=[[FR_History_Identity_ViewController alloc]init];
       
        [self.navigationController pushViewController:VC animated:YES];
        
    }else {
        FR_Par_HistoryViewController *VC=[[FR_Par_HistoryViewController alloc]init];
        
        [self.navigationController pushViewController:VC animated:YES];
    }
    
}

- (void)functionAction:(UIGestureRecognizer *)tap {
    
    SY_FunctionView *funView = (SY_FunctionView *)tap.view;
    
    //int tag = (int)funView.tag;
    NSString *str = funView.label.text;
    
    if ([str isEqualToString:@"请假"]) {
        [self fun_leaveAction];
    }else if ([str isEqualToString:@"考勤"]){
        [self fun_attendAction];
    }else if ([str isEqualToString:@"迟到"]){
        [self fun_lateAction];
    }else if ([str isEqualToString:@"旷课"]){
        [self fun_absenceAction];
    }else if ([str isEqualToString:@"统计"]){
        [self fun_accountAction];
    }else if ([str isEqualToString:@"底片"]){
        [self fun_photoAction];
    }else if ([str isEqualToString:@"访客"]){
        [self fun_visitorsAction];
    }else if ([str isEqualToString:@"菜谱"]){
        [self fun_foodAction];
    }else if ([str isEqualToString:@"通知"]){
        [self fun_notiAction];
    }else if ([str isEqualToString:@"作业"]){
        [self fun_taskAction];
    }else if ([str isEqualToString:@"校园风采"]){
       [self fun_campusAction];
    }else if ([str isEqualToString:@"班级动态"]){
       [self fun_dynamicsAction];
    }else if ([str isEqualToString:@"校园收费"]){
       [self fun_schoolPayAction];
    }


}

- (void)fun_schoolPayAction{
   
   if ([lasttype isEqualToString:@"1"]) {
      SY_Tch_OrdersViewController *payVC = [[SY_Tch_OrdersViewController alloc]init];
      
      [self.navigationController pushViewController:payVC animated:YES];
   }else {
      SY_Par_PaymentListViewController *payVC = [[SY_Par_PaymentListViewController alloc]init];
      
      [self.navigationController pushViewController:payVC animated:YES];
   }
}

- (void)fun_campusAction{
   
   SY_WebViewController * web = [[SY_WebViewController alloc]init];
   web.urlStr = [NSString stringWithFormat:@"http://m.our100.net/function/xyfc/list.aspx?userid=%@",USERID];
   [self.navigationController pushViewController:web animated:YES];
}

- (void)fun_dynamicsAction{
   
   SYNewDynamicViewController *fDynamicVC=[[SYNewDynamicViewController alloc]init];
   [self.navigationController pushViewController:fDynamicVC animated:YES];
}
- (void)fun_notiAction{
   
   SYNotiViewController *notiVC = [[SYNotiViewController alloc] init];
   [self.navigationController pushViewController:notiVC animated:YES];
}

- (void)fun_taskAction{
   
   SYHomeworkViewController *homeVC = [[SYHomeworkViewController alloc] init];
   [self.navigationController pushViewController:homeVC animated:YES];
}

- (void)fun_leaveAction {
    
    if ([lasttype isEqualToString:@"1"]) {
        SY_Home_TeaLeavingViewController *leaveVC=[[SY_Home_TeaLeavingViewController alloc]init];
        
        [self.navigationController pushViewController:leaveVC animated:YES];
    }else {
        HomeParLeaveListController *leaveListVC=[[HomeParLeaveListController alloc]init];
        
        [self.navigationController pushViewController:leaveListVC animated:YES];
    }
}

- (void)fun_attendAction {
      
      if ([lasttype isEqualToString:@"1"]) {
         SY_Tch_AttendanceViewController *tchVC = [[SY_Tch_AttendanceViewController alloc]init];
         
         [self.navigationController pushViewController:tchVC animated:YES];
      }else {
         
         SY_Par_AttendanceViewController *parVC = [[SY_Par_AttendanceViewController alloc] init];
         
         [self.navigationController pushViewController:parVC animated:YES];
      }
   
    
}

- (void)fun_lateAction {
    
    if ([lasttype integerValue] == 1) {
     
        FR_LateViewController *vc = [[FR_LateViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        
    }else {
        
        FR_Par_Attendance_ViewController *vc = [[FR_Par_Attendance_ViewController alloc] init];
        vc.arrival = 2;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)fun_absenceAction {
    
    if ([lasttype integerValue] == 1) { //老师身份
        
        FR_AbsentClass_ViewController *vc = [[FR_AbsentClass_ViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }else { //家长身份
        
        FR_Par_Attendance_ViewController *vc = [[FR_Par_Attendance_ViewController alloc] init];
        vc.arrival = 0;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)fun_accountAction {
    
    if ([lasttype isEqualToString:@"1"]) {
        
        if ([SYAccountTool ShareAccount].account.schoolManage > 0) {
            
            SY_SchoolFormViewController * VC = [[SY_SchoolFormViewController alloc]init];
            
            [self.navigationController pushViewController:VC animated:YES];
            
        }else if ([SYAccountTool ShareAccount].account.haveclass > 0)
        {
            
            SY_TeacherFormViewController * VC = [[SY_TeacherFormViewController alloc]init];
            
            [self.navigationController pushViewController:VC animated:YES];
            
        }
        
    }else
    {
        SY_ParentFormViewController * VC = [[SY_ParentFormViewController alloc]init];
        
        [self.navigationController pushViewController:VC animated:YES];

    }
}

- (void)fun_photoAction {
    
    FR_ManagerInfoViewController *vc = [[FR_ManagerInfoViewController alloc] init];
//    [self.navigationController pushViewController:vc animated:YES];
    
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    
    nav.navigationBar.backgroundColor = [UIColor whiteColor];
    nav.navigationBar.barTintColor = [UIColor whiteColor];
    [nav.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor],NSFontAttributeName:[UIFont boldSystemFontOfSize:18.0]}];
    
    CATransition *animation = [CATransition animation];
    animation.duration = 0.25;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
    animation.type = kCATransitionPush;
    animation.subtype = kCATransitionFromRight;
    [self.view.window.layer addAnimation:animation forKey:nil];
    
    [self presentViewController:nav animated:NO completion:NULL];
}

- (void)fun_visitorsAction {
    
    FR_VisitortViewController *vc =[[FR_VisitortViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)fun_foodAction
{
      FoodListViewController *leaveVC=[[FoodListViewController alloc]init];
   
      [self.navigationController pushViewController:leaveVC animated:YES];
}

#pragma mark - Request

- (void)getAttendanceCount {
    
    NSMutableDictionary * param = [[NSMutableDictionary alloc] initWithCapacity:0];
    [param setObject:USERID forKey:@"userid"];
    
    [param setObject:@"0" forKey:@"scid"];
    if ([lasttype isEqualToString:@"1"]) {
        if ([SYAccountTool ShareAccount].account.schoolManage > 0){//管理员
            [param setObject:@"2" forKey:@"role"];
            [param setObject:[NSString stringWithFormat:@"%lld",[SYAccountTool ShareAccount].account.schoolManage] forKey:@"scid"];
            
        }else {//班主任
            [param setObject:@"1" forKey:@"role"];
        }
        
    }else if ([lasttype isEqualToString:@"2"]){
        [param setObject:@"0" forKey:@"role"];
    }
    
    [Utils noHUD_Java_get:@"api/getAttendanceCount" parameters:param success:^(NSInteger recode, id jsonObject) {
        
        NSDictionary * dic = (NSDictionary *)jsonObject;
        
        NSDictionary *re_data = [dic objectForKey:@"re_data"];
        
        NSString *leaveCount = [[re_data objectForKey:@"leave"] integerValue] > 99?@"99+":[NSString stringWithFormat:@"%@",[re_data objectForKey:@"leave"]];
        NSString *lateCount = [[re_data objectForKey:@"late"] integerValue] > 99?@"99+":[NSString stringWithFormat:@"%@",[re_data objectForKey:@"late"]];
        NSString *absenceCount = [[re_data objectForKey:@"absent"] integerValue] > 99?@"99+":[NSString stringWithFormat:@"%@",[re_data objectForKey:@"absent"]];
        
        if ([leaveCount isEqualToString:@"99+"]) {
            [top_LeaveView.countLabel setFont:[UIFont systemFontOfSize:18]];
        }
        if ([lateCount isEqualToString:@"99+"]) {
            [top_LateView.countLabel setFont:[UIFont systemFontOfSize:18]];
        }
        if ([absenceCount isEqualToString:@"99+"]) {
            [top_AbsenceView.countLabel setFont:[UIFont systemFontOfSize:18]];
        }
        
        top_LeaveView.countLabel.text = leaveCount;
        top_LateView.countLabel.text = lateCount;
        top_AbsenceView.countLabel.text = absenceCount;
        
        [self.baseScrollView.mj_header endRefreshing];
        
        
    } failure:^(NSInteger recode, NSError *error) {
        [self.baseScrollView.mj_header endRefreshing];
    }];
}

//加载广告图片
- (void)loadAdvImage{
    
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    [dict setObject:@"api_startpic_list" forKey:@"method"];
    [dict setObject:@"6" forKey:@"type"];
    if (USERID) {
        
        [dict setObject:USERID forKey:@"userid"];
    }
    
    __weak FR_HomeViewController *VC = self;
    [Utils noHUD_get:nil parameters:dict success:^(NSInteger recode, id jsonObject) {
    
        NSDictionary * dic = (NSDictionary *)jsonObject;
        
        NSMutableArray * dataArr = [[NSMutableArray alloc]initWithArray:[dic objectForKey:@"re_data"]];
        self.advImageArray = dataArr;
        
        if (dataArr.count == 0) {
            
            UIImage *image = [UIImage imageNamed:@"unPic"];
            
            UIImageView *view = [[UIImageView alloc] initWithImage:image];
            
            view.frame = self.advScrollView.bounds;
            view.image = image;
            view.contentMode = UIViewContentModeScaleAspectFill;
            view.clipsToBounds = YES;
            [self.advScrollView addSubview:view];
            
            return;
        }
        
        //这些判断是防止只有一张图片的时候出现滑屏
        int num = 0;
        float x_offset = 0;
        if (dataArr.count > 1) {
            
            num = 2;
            x_offset = SCREENWIDTH;
        }
        
        self.advScrollView.contentSize = CGSizeMake((num + dataArr.count) * self.advScrollView.frame.size.width, 84);
        self.advScrollView.contentOffset = CGPointMake(x_offset, 0);
        
        for (UIView *view in self.advScrollView.subviews) {
            [view removeFromSuperview];
        }
        
        for (int i = 0; i < (dataArr.count > 1 ?  dataArr.count + 2 : dataArr.count); i++) {
            
            NSDictionary *logoDic;
            UIImageView *imageView = [[UIImageView alloc] init];
            
            if (i == 0) {  //第一张
                
                logoDic = [dataArr objectAtIndex:dataArr.count - 1];
                
            }else if(i == dataArr.count + 1){ //最后一张
                
                logoDic = [dataArr objectAtIndex:0];
                
            }else{
                
                logoDic = [dataArr objectAtIndex:i - 1];
            }
            
            NSString * pic = [logoDic objectForKey:@"pic"];
            NSString * picURL = [NSString stringWithFormat:@"%@%@",IMAGEHOSTURL,pic];
            
            imageView.frame = CGRectMake(i * self.advScrollView.frame.size.width, 0, self.advScrollView.frame.size.width, 160);
            imageView.contentMode = UIViewContentModeScaleAspectFill;
            imageView.clipsToBounds = YES;
            imageView.tag = i;
            imageView.userInteractionEnabled = YES;
            
            [imageView sd_setImageWithURL:[NSURL URLWithString:picURL] placeholderImage:nil];
            
            [self.advScrollView addSubview:imageView];
            
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(advAction:)];
            [imageView addGestureRecognizer:tap];
            
            VC.advImageLoadSuccess = YES;
        }
        
        if (self.advImageArray.count > 1) {
            //指示器
            [self.advPageControl removeFromSuperview];
            self.advPageControl = [[UIPageControl alloc] init];
            [self.baseScrollView addSubview:self.advPageControl];
            
            [self.advPageControl mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.equalTo(self.advScrollView.mas_centerX).offset(0);
                make.bottom.equalTo(self.advScrollView.mas_bottom).offset(5);
                make.width.equalTo(@100);
                make.height.equalTo(@30);
            }];
            
            self.advPageControl.numberOfPages = dataArr.count;
            self.advPageControl.currentPage = 0;
            [self.advPageControl addTarget:self action:@selector(pagecontrolChange:) forControlEvents:UIControlEventValueChanged];
            self.advPageControl.backgroundColor = [UIColor clearColor];
            
            self.advPageControl.pageIndicatorTintColor = [UIColor colorWithHexString:@"#a3e0ff"];
            self.advPageControl.currentPageIndicatorTintColor = [UIColor colorWithHexString:@"#66cbff"];
        }
        
        
        
        VC.pldImageView = nil;
        [VC.pldImageView removeFromSuperview];
        
        
    } failure:^(NSInteger recode, NSError *error) {
        
        UIImage *image = [UIImage imageNamed:@"unPic"];
        
        UIImageView *view = [[UIImageView alloc] initWithImage:image];
        
        view.frame = self.advScrollView.bounds;
        view.image = image;
        view.contentMode = UIViewContentModeScaleAspectFit;
        
        [view sd_setImageWithURL:[NSURL URLWithString:@"123"] placeholderImage:image];
        
        view.frame = self.advScrollView.bounds;
        //view.image = image;
        
        [self.advScrollView addSubview:view];
        
        VC.pldImageView = nil;
        [VC.pldImageView removeFromSuperview];
        
    }];
    
}


#pragma mark - ScrollViewdelegate

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
    if (scrollView == self.advScrollView) {
        
        [advImgtimer invalidate];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    if (scrollView == self.advScrollView) {
        
        advImgtimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(switchAdvImg) userInfo:nil repeats:YES];
        
    }
}

//pageControl的值改变
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    CGPoint point = scrollView.contentOffset;
    
    if (scrollView == self.advScrollView) {
        
        int page = point.x / SCREENWIDTH;
        
        if (page == self.advImageArray.count + 1) {
            
            scrollView.contentOffset = CGPointMake(SCREENWIDTH, 0);
            
            page = 0;
            
        }else if (page == 0){
            
            scrollView.contentOffset = CGPointMake(SCREENWIDTH * self.advImageArray.count, 0);
            page = (int)self.advImageArray.count - 1;
            
        }else{
            
            page--;
        }
        
        self.advPageControl.currentPage = page;
        
        
    }
    
}
//scrollView偏移
-(void)pagecontrolChange:(id)sender{
    
    CGPoint point = self.advScrollView.contentOffset;
    
    point.x = self.advPageControl.currentPage *SCREENWIDTH;
    
    [UIView animateWithDuration:0.4 animations:^{
        
        self.advScrollView.contentOffset = point;
    }];
    
}

#pragma mark - Get

- (UIScrollView *)baseScrollView {
    
    if (_baseScrollView == nil) {
        _baseScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, SafeAreaTopHeight, SCREENWIDTH, SCREENHEIGH  - SafeAreaTopHeight - SafeAreaBottomHeight - 49)];
        [_baseScrollView setContentSize:CGSizeMake(SCREENWIDTH, SCREENHEIGH  - 49 +1)];
        _baseScrollView.delegate = self;
        _baseScrollView.scrollEnabled = YES;
        _baseScrollView.showsHorizontalScrollIndicator = NO;
        _baseScrollView.showsVerticalScrollIndicator = NO;
        [_baseScrollView setBackgroundColor:[UIColor whiteColor]];
        _baseScrollView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            
            [self getAttendanceCount];
        }];
        
    }
    
    return _baseScrollView;
}

- (UIScrollView *)advScrollView {
    if (_advScrollView == nil) {
        
        _advScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 160)];
        _advScrollView.delegate = self;
        _advScrollView.scrollEnabled = YES;
        _advScrollView.showsHorizontalScrollIndicator = NO;
        _advScrollView.pagingEnabled = YES;
        [_advScrollView setBackgroundColor:[UIColor whiteColor]];
    }
    return _advScrollView;
}

- (void)requestData
{
   
   NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
   
   [dict setObject:@"api_info_noreadnum" forKey:@"method"];
   
   
   [dict setObject:USERID forKey:@"userid"];
   
   [dict setObject:lasttype forKey:@"usertype"];
   
   [Utils noIndiGet:nil parameters:dict success:^(NSInteger recode, id jsonObject) {
      //通知
      NSInteger not = [[jsonObject objectForKey:@"noticenum"] integerValue];
      //作业
      NSInteger tas = [[jsonObject objectForKey:@"tasknum"] integerValue];
      
      
      //通知
      if (not > 0) {
         
         self->notiView.unreadView.hidden = NO;
         NSString *notiStr = [jsonObject objectForKey:@"noticenum"];
         self->notiView.unreadLabel.text = notiStr;
         
         if (notiStr.length > 2){
            
            [self->notiView.unreadLabel mas_updateConstraints:^(MASConstraintMaker *make) {
               
               make.width.equalTo(@30);
               
            }];
            
            [self->notiView.unreadView mas_updateConstraints:^(MASConstraintMaker *make) {
               
               make.width.equalTo(@30);
               
            }];
            
         }else if (notiStr.length <= 2){
            
            [self->notiView.unreadLabel mas_updateConstraints:^(MASConstraintMaker *make) {
               
               make.width.equalTo(@18);
               
            }];
            
            [self->notiView.unreadView mas_updateConstraints:^(MASConstraintMaker *make) {
               
               make.width.equalTo(@18);
               
            }];
         }
         
      }else{
         
         self->notiView.unreadView.hidden = YES;
      }
      
      //作业
      if (tas > 0) {
         
         self->tasView.unreadView.hidden = NO;
         NSString *tasStr = [jsonObject objectForKey:@"tasknum"];
         self->tasView.unreadLabel.text = tasStr;
         
        if (tasStr.length > 2) {
           
           [self->tasView.unreadLabel mas_updateConstraints:^(MASConstraintMaker *make) {
              
              make.width.equalTo(@30);
           
           }];
           
           [self->tasView.unreadView mas_updateConstraints:^(MASConstraintMaker *make) {
              
              make.width.equalTo(@30);
              
           }];
           
        }else if (tasStr.length <= 2){
           
           [self->tasView.unreadLabel mas_updateConstraints:^(MASConstraintMaker *make) {
              
              make.width.equalTo(@18);
              
           }];
           
           [self->tasView.unreadView mas_updateConstraints:^(MASConstraintMaker *make) {
              
              make.width.equalTo(@18);
              
           }];
        }
         
      }else{
         
         self->tasView.unreadView.hidden = YES;
      }
      
   
      
   } failure:^(NSInteger recode, NSError *error) {
      
   }];
   
}

@end

